package com.chc.exer;

/**
 * @Author: chc
 * @Date: 2024/11/10/16:30
 * @Description: 多线程--复习
 */
public class ThreadExer {


    public static void main(String[] args) throws InterruptedException {
        //1 继承Thread方式的多线程
        // ThreadTest test = new ThreadTest();
        // test.start();
        // for (int i = 0; i < 5; i++) {
        //     System.out.println(Thread.currentThread().getName());
        // }
        //2 实现Runnable接口的多线程
        ThreadTest2 threadTest2 = new ThreadTest2();
        new Thread(threadTest2).start();
        // 睡眠六秒，通知线程停止
        Thread.sleep(6000);
        threadTest2.setFlag(false);
    }


    //实现线程的方式一 (继承Thread类)
    static class ThreadTest extends Thread{
        @Override
        public void run() {
            for (int i = 0; i < 50; i++){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName());
            }
        }
    }

    // 实现多线程方式二 (实现Runnable接口)
    static class ThreadTest2 implements Runnable{


        private Boolean flag = true;

        public void setFlag(Boolean flag) {
            this.flag = flag;
        }

        @Override
        public void run() {
            while (flag){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("实现Runnable接口方式的多线程"+Thread.currentThread().getName());
            }
        }
    }
}
